require 'rexml/element'
require 'rexml/document'

class Settings
  
  attr_accessor :username
  attr_accessor :password
  attr_accessor :download_location
  attr_accessor :max_concurrent_downloads
  
  def initialize
    @username = ""
    @password = ""
    @download_location = ""
    @max_concurrent_downloads = 1
  end
  
  
  def save
    root = REXML::Element.new "settings"
    
    el_user = REXML::Element.new "username"
    el_user.add_text @username
    
    el_password = REXML::Element.new "password"
    el_password.add_text @password
    
    el_download_location = REXML::Element.new "downloadlocation"
    el_download_location.add_text @download_location
    
    el_max_concurrent_downloads = REXML::Element.new "maxconcurrentdownloads"
    el_max_concurrent_downloads.add_text @max_concurrent_downloads
    
    root.add(el_user)
    root.add(el_password)
    root.add(el_download_location)
    root.add(el_max_concurrent_downloads)
    
    doc = REXML::Document.new
    doc.add_element(root)
    
    open("settings.xml", "w") { |file|
      file.write(doc)
    }
    
  end
  
  # try to load settings file
  # when settings.xml file is not found
  # return new settings
  def self.load
    begin
      s = Settings.new
      doc = REXML::Document.new File.new("settings.xml")
      s.username = doc.root.elements["username"].text
      s.password = doc.root.elements["password"].text
      s.download_location = doc.root.elements["downloadlocation"].text
      s.max_concurrent_downloads = doc.root.elements["maxconcurrentdownloads"].text
      return s
    rescue Exception
      default_settings = Settings.new
      return default_settings
      return s
    end
  end
  
  
end
